/**
 * 
 */
package com.geezdata.cps.sdk3rd.wechat.method;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.geezdata.cps.base.utils.HttpClientUtil;
import com.geezdata.cps.sdk3rd.wechat.request.WechatMediaUploadRequest;
import com.geezdata.cps.sdk3rd.wechat.response.WechatMediaUploadResult;

/**
 * @author tfwan
 * @date 创建时间：2018年7月5日 下午4:23:54
 *
 */
public class WechatMediaUpload extends BaseWechat implements Wechat<WechatMediaUploadRequest, WechatMediaUploadResult> {
	private static final Logger logger = LoggerFactory.getLogger(WechatMediaUpload.class);
	private static final String MEDIA_UPLOAD = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=";
	
	@Override
	public WechatMediaUploadResult execute(WechatMediaUploadRequest request) {
		String respJson =null;
		byte[] imgByte = null;
		File file = null;
        try {
        	imgByte = HttpClientUtil.getByte(request.getMedia());
        	InputStream in = new ByteArrayInputStream(imgByte);
            file=new File("","text.jpg");
            FileOutputStream fos = null;
        	fos = new FileOutputStream(file);
        	byte[] b = new byte[1024];
            int nRead = 0;
        	while ((nRead = in.read(b)) != -1) {
			    fos.write(b, 0, nRead);
			}
			fos.flush();
			fos.close();
	        in.close();
		} catch (IOException e) {
			logger.error("WechatMediaUploadResult::file failed ");
		}
		respJson = HttpClientUtil.postFormData(MEDIA_UPLOAD + request.getToken()+"&type=image", file);
		JSONObject jsonObject = JSONObject.parseObject(respJson);
		WechatMediaUploadResult  result = JSONObject.toJavaObject(jsonObject,WechatMediaUploadResult.class);
		return result;
	}
}

